package toolNet 
{
	
	import com.cjson.CJSON;
	
	import flash.events.StatusEvent;
	import flash.net.LocalConnection;

	public class Connection
	{
		//本地客户端通讯
		public static var _conn			:	LocalConnection;
		public static var _connName		:	String;
		public static var _methodName	:	String	=	"receiveTool";
		
		private 		 var _start			:	Boolean	=	true;
		
		private 		 var _toolLogic		:	ToolLogic;
		
		public function Connection()
		{
		}
		
		/**
		 *	链接关键字 
		 * @param key	玩家的名字作为唯一关键字
		 * 
		 */
		public function createConnection(connectionName : String):void
		{
			_connName		=	connectionName;
			_conn			=	new LocalConnection();
			_conn.client	=	this;
			_conn.allowDomain("*")

			_conn.addEventListener(StatusEvent.STATUS, onStatus);
			
			try {
				_conn.connect( _connName );
			} catch (error:ArgumentError) {
//				trace("Can't connect...the connection name is already being used by another SWF");
			}
		}
			
		private function onStatus(evt : StatusEvent):void
		{
			switch (evt.level) {
				case "status":
//					trace("LocalConnection.send() succeeded");
					break;
				case "error":
//					trace("LocalConnection.send() failed");
					break;
			}
		}
		
		/**
		 *	发送 
		 * @param parameters	参数...
		 * 
		 */
		public function send(...parameters):void
		{
			if(_conn == null || !_start)
			{//当连接没有建立|\没有启动debug工具的时候，返回
				return;
			}
			
			_conn.send(_connName + "tool", _methodName, CJSON.encode(parameters));
		}
		
		/**
		 *	发送场景数据(由于数据太多，特殊处理)
		 */
		public function sendScene(msgId : String, scene : Object):void
		{
			if(_conn == null || !_start)
			{//当连接没有建立|\没有启动debug工具的时候，返回
				return;
			}
			
			//发送开始信息
			_conn.send(_connName + "tool", _methodName, CJSON.encode([msgId, "start"]));
			
			//sceneStr > 40k报错
			
			var sceneStr	:	String	=	CJSON.encode(ObjectUtil.DecodeVo(scene));
			
			var fen			: 	int		=	Math.ceil(sceneStr.length / 30000); 
			//拆分sceneStr,分5段
			var leng		:	int		=	sceneStr.length / fen;
			
			
			var str			:	String	=	"";
			for(var i : int	 = 1; i <= fen; i++)
			{
				if(i != fen)
				{
					str	=	sceneStr.substr((i - 1) * leng, leng);
				}else
				{
					str	=	sceneStr.substr((i - 1) * leng, sceneStr.length - (i - 1) * leng) + "$";
				}
				_conn.send(_connName + "tool", _methodName, CJSON.encode([msgId, str]));
			}
		}
		
		public function receive(data : String):void 
		{
			if(_toolLogic == null)
			{
				_toolLogic	=	new ToolLogic();
			}
			
			var pList		:	Array		=	CJSON.decode(data);
			_toolLogic.logic(pList[0], pList[1]);
		}

		public function set start(value:Boolean):void
		{
			_start = value;
		}

	}
}